package com.xxx.dynamicproxy;

import java.io.FileOutputStream;
import java.io.IOException;

import sun.misc.ProxyGenerator;

public class GenerateClassFile {
	
	/**
	 * 使用动态代理对象，生成字节码文件，并存储到磁盘
	 * @param clazz  Class对象
	 * @param proxyName 代理类名称
	 */
	public static void generateClassFile(Class clazz, String proxyName) {
		byte[] proxyClassFile = ProxyGenerator.generateProxyClass(
                proxyName, new Class[] {clazz});
		String path = clazz.getResource(".").getPath(); // 当前目录
		System.out.println(path);
		
		FileOutputStream out = null;
		
		try {
			out = new FileOutputStream(path + proxyName + ".class");
			out.write(proxyClassFile);
			out.flush();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
	}

}
